/** 服务工具 */
import {UserMsg, UserMsgStore, LoginForm} from '@/interface/user/entity/UserEntityInterface';
import {UserService} from '@/utils/ApiRequest';
import Cache from '@/utils/Cache';
import router from "@/router";

/** 工具服务 */
const cache = new Cache(), userService = new UserService();
/** 方法名称集合 */
const LOGIN_SUCCESS = 'loginSuccess', LOGOUT_SUCCESS = 'logOutSuccess', GET_USER_COUNT = 'getUserCount';
/** key 集合 */
const USER_MSG_KEY = 'userMsg', LOGIN_STATUS = 'loginStatus', TOKEN_CACHE_KEY = 'token';
export default {
  namespaced: true,
  /** 基本对象 */
  state: {
    userMsg: new UserMsgStore(),
    userCount: 0
  },
  /** 计算函数 */
  getters: {
    /** 获取 userMsg */
    userMsg: (state: any) => {
      // 判断 state 中 userMsg 信息是否为空
      if ((state.userMsg as UserMsgStore).isEmpty()) {
        // 如果空的话从 storage 获取并返回 UserMsg | undefined
        let userMsg = cache.get('userMsg'), ums: UserMsgStore = new UserMsgStore();
        if (userMsg) {
          ums = new UserMsgStore((userMsg as UserMsg));
          state.userMsg = ums;
        }
        return ums;
      }
      // 否则直接返回
      return state.userMsg;
    },
    /** 登录状态 */
    loginStatus: (state: any, getters: any) => {
      let userMsg: UserMsgStore;
      return (userMsg = getters.userMsg) && !userMsg.isEmpty();
    },
    /** 用户总数 */
    getUserCount: (state: any) => state.userCount
  },
  /** 同步函数 */
  mutations: {
    /** 将 userMsg set 入 state 和 cache 当中 */
    loginSuccess(state: any, userMsg: UserMsg) {
      state.userMsg = new UserMsgStore(userMsg);
      cache.set(USER_MSG_KEY, userMsg);
    },
    /** 登出后清除 state 缓存 */
    logOutSuccess(state: any) {
      state.userMsg = new UserMsgStore();
      cache.remove(USER_MSG_KEY);
      router.push({
        path: '/'
      });
    },
    /** 保存用户总数 */
    getUserCount(state: any, count: number) {
      state.userCount = count;
    }
  },
  /** 异步函数 */
  actions: {
    /** 登录 */
    async login({commit}: any, loginForm: LoginForm) {
      let res = await userService.login(loginForm);
      // res 存在则意味登录成功,调用 mutations setUserMsg
      if (res) {
        commit(LOGIN_SUCCESS, res as UserMsg);
        return res;
      }
    },
    /** 登出
     * <p>登出只需要清除网站的缓存信息即可</p>
     */
    async logOut({commit}: any) {
      commit(LOGOUT_SUCCESS);
      cache.remove(TOKEN_CACHE_KEY);
    },
    /** 保存用户总数 */
    async getUserCount({commit}: any) {
      let res = await userService.getUserCount();
      if (res) {
        commit(GET_USER_COUNT, res.data);
        return res.data;
      }
    }
  }
}